package com.shengwei.truck.driver.view.ui.mine.userinfo;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityOptionsCompat;
import androidx.lifecycle.Observer;
import com.bumptech.glide.Glide;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.shengwei.truck.driver.view.ui.app.MyApplication;
import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.JsonCurUserInfoData;
import com.shengwei.truck.driver.bean.JsonStatisticsOneDayData;
import com.shengwei.truck.driver.bean.MyDateTimeField;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.User;
import com.shengwei.truck.driver.databinding.FragmentMineBinding;
import com.shengwei.truck.driver.utils.DateTimeUtils;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.view.ui.BaseFragment;
import com.shengwei.truck.driver.view.ui.MainActivity;
import com.shengwei.truck.driver.view.ui.settings.SettingsActivity;
import com.shengwei.truck.driver.view.ui.app.WebViewBrowser;
import com.shengwei.truck.driver.view.ui.statistic.HistroyStatisticActivity;
import com.shengwei.truck.driver.view.ui.task.ExcepTaskListActivity;
import com.shengwei.truck.driver.vm.MineViewModel;

/**
 * 我的TAB页，显示我的基本信息、我的任务单、设置等菜单
 */
public class MineFragment extends BaseFragment<MineViewModel, FragmentMineBinding> implements View.OnClickListener {
    public String mPersonName;
    public String mHeadImvUrl; //头像URL
    public String mMobile;
    public String mIdentify; //身份证号
    public String mCarNum; //车牌号
    public long mStartTimeMill;  //提交给服务器的参数：当天0点
    public long mEndTimeMill;    //提交给服务器的参数：当天此刻时间

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = super.onCreateView(inflater, container, savedInstanceState);
        initView();
        initLiveDataObersve();
        //刷新统计面板

        return root;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        MyLogCat.i("MineFragment", "onActivityCreated");
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        MyLogCat.i("MineFragment", "onStart");
        if (MainActivity.mCurTabIndex == 3) {
            mViewModel.getUserInfo();
            refreshDayStatistics();
        }
        super.onStart();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        MyLogCat.i("MineFragment", "onHiddenChanged");
         initAvatarImv();
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onResume() {
        MyLogCat.i("MineFragment", "onResume");
        super.onResume();
    }

    @Override
    public void onPause() {
        MyLogCat.i("MineFragment", "onPause");
        super.onPause();
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_mine;
    }

    private void initView() {
        mDataBinding.settingsLayout.setOnClickListener(this);
        mDataBinding.userInfoLayout.setOnClickListener(this);
        //gxw-mDataBinding.questionLayout.setOnClickListener(this);
        mDataBinding.exceptionTaskLayout.setOnClickListener(this);
        mDataBinding.statisticMainLayout.statisticDayLayout.setOnClickListener(this);
    }

    /**
     * 更新UI上的时间
     */
    public void updateDateTimeUI(){
        mStartTimeMill = DateTimeUtils.getTimesmorningMs();
        mEndTimeMill = System.currentTimeMillis();
        MyDateTimeField myDateTimeField = DateTimeUtils.getTimeFieldObject(mEndTimeMill);
        //年月日
        String strDateBuilder = myDateTimeField.year + "年" +
                myDateTimeField.month + "月" +
                myDateTimeField.day + "日";
        mDataBinding.statisticMainLayout.tvDate.setText(strDateBuilder);

    /*    //时分秒
        String strTimeBuilder = myDateTimeField.hour + ":" +
                myDateTimeField.min + ":" +
                myDateTimeField.second;
        mDataBinding.statisticMainLayout.tvTodayTime.setText(strTimeBuilder);*/
    }

    /**
     * 更新此刻时间，并从服务器获取最新统计
     */
    public void refreshDayStatistics() {
        updateDateTimeUI();
        String ymd=  DateTimeUtils.getDateTimeYMD(mStartTimeMill);
        mViewModel.getStatisticOneDay(ymd);
    }

    /**
     * 初始化头像图片，使用本地缓存先显示
     */
    public void initAvatarImv() {
        String imvHeadUrl = User.getInstance(getActivity()).getHeadImvUrl();
        if(!TextUtils.isEmpty(imvHeadUrl)){
            Glide.with(getActivity()).load(imvHeadUrl).into(mDataBinding.imvHeadPhoto);
        }
    }

    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {

        mViewModel.getCurUserInfo().observe(getViewLifecycleOwner(), new Observer<Result<JsonCurUserInfoData>>() {
            @Override
            public void onChanged(Result<JsonCurUserInfoData> jsonCurUserInfoDataResult) {
                jsonCurUserInfoDataResult.handler(new OnCallback<JsonCurUserInfoData>() {
                    @Override
                    public void onSuccess(JsonCurUserInfoData data) {
                        updateUserInfo(data);
                    }
                });
            }
        });

        mViewModel.getStatisticData().observe(getViewLifecycleOwner(), new Observer<Result<JsonStatisticsOneDayData>>() {
            @Override
            public void onChanged(Result<JsonStatisticsOneDayData> jsonCurUserInfoDataResult) {
                jsonCurUserInfoDataResult.handler(new OnCallback<JsonStatisticsOneDayData>() {
                    @Override
                    public void onSuccess(JsonStatisticsOneDayData data) {
                        updateStasticsUI(data);
                    }
                });
            }
        });
    }

    /**
     * 显示统计数据
     * @param data
     */
    private void updateStasticsUI(JsonStatisticsOneDayData data) {
        mDataBinding.statisticMainLayout.loadWeightValue.setText(data.getLaTotal());
        mDataBinding.statisticMainLayout.unLoadWeightValue.setText(data.getUaTotal());
        mDataBinding.statisticMainLayout.timesValue.setText(data.getTrainNumber());
        mDataBinding.statisticMainLayout.tvPlanValue.setText(data.getTaskTotal()+"吨");
    }

    /**
     * 更新用户信息
     */
    private void updateUserInfo(JsonCurUserInfoData data) {
        mPersonName = data.getRealName();
        mMobile = data.getPhone();
        mHeadImvUrl = data.getAvatar();
        mIdentify = data.getIdCard();
        mCarNum = data.getVehiclePlateNumber();
        mDataBinding.setMobile(mMobile);
        mDataBinding.setPersonName(mPersonName);

        if(TextUtils.isEmpty(mPersonName)||TextUtils.isEmpty(mIdentify)){
            mDataBinding.unCompleteInfo.setVisibility(View.VISIBLE);
        }
        else{
            mDataBinding.unCompleteInfo.setVisibility(View.GONE);
        }
        ImageLoader.getInstance().displayImage(mHeadImvUrl, mDataBinding.imvHeadPhoto, MyApplication.options);
        if(mHeadImvUrl != null){
            User user = User.getInstance(getActivity());
            user.setHeadImvUrl(mHeadImvUrl);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.statisticDayLayout:
                goHistroyStatistic();
                break;
            case R.id.userInfoLayout:
              //gxw- 大家适应不了转场动画  ActivityOptionsCompat activityOptionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(),mDataBinding.imvHeadPhoto,"imv_head");
                Intent intent = new Intent(mContext, PersonalInfoActivity.class);
                intent.putExtra("headImvUrl", mHeadImvUrl);
                intent.putExtra("name", mPersonName);
                intent.putExtra("identify", mIdentify);
                intent.putExtra("mobile", mMobile);
                intent.putExtra("carNum", mCarNum);
                startActivity(intent);
                break;
            case R.id.settingsLayout: //系统设置
                Intent intentSet = new Intent(mContext.getApplicationContext(), SettingsActivity.class);
                startActivity(intentSet);
                break;
            case R.id.questionLayout: //常见问题
                Intent intentQue = new Intent(mContext.getApplicationContext(), WebViewBrowser.class);
                String title = this.getResources().getString(R.string.frequnce_question);
                intentQue.putExtra("url", "https://www.baidutitle.com");
                intentQue.putExtra("title", title);
                startActivity(intentQue);
                break;
            case R.id.exceptionTaskLayout: //异常任务
                Intent intentExce = new Intent(mContext.getApplicationContext(), ExcepTaskListActivity.class);
                startActivity(intentExce);
                break;
        }
    }

    /**
     * 跳转到历史统计页面
     */
    public void goHistroyStatistic(){
        String strDate = mDataBinding.statisticMainLayout.tvDate.getText().toString();
        String strLoadWeight = mDataBinding.statisticMainLayout.loadWeightValue.getText().toString();
        String strUnLoadWeight = mDataBinding.statisticMainLayout.unLoadWeightValue.getText().toString();
        String strTimes = mDataBinding.statisticMainLayout.timesValue.getText().toString();

        Intent intent = new Intent(mContext.getApplicationContext(), HistroyStatisticActivity.class);
        intent.putExtra("date",strDate);
        intent.putExtra("loadWeight",strLoadWeight);
        intent.putExtra("unLoadWeight",strUnLoadWeight);
        intent.putExtra("times",strTimes);
        startActivity(intent);
    }

}